<template>
  <div class="knowledge-container">
    <el-container>
      <el-aside width="280px">
        <el-card class="category-tree">
          <template #header>
            <div class="card-header">
              <span>知识分类</span>
              <el-button type="primary" link @click="handleAddCategory">
                <el-icon>
                  <Plus />
                </el-icon> 添加分类
              </el-button>
            </div>
          </template>

          <el-tree 
            ref="treeRef"
            :data="categories" 
            :props="defaultProps" 
            @node-click="handleNodeClick" 
            :current-key="currentCategory?.id"
            :highlight-current="true"
            default-expand-all
            class="custom-tree">
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span class="node-label">
                  <el-icon v-if="!data.children || data.children.length === 0">
                    <Document />
                  </el-icon>
                  <el-icon v-else>
                    <Folder />
                  </el-icon>
                  {{ node.label }}
                </span>
                <span class="node-actions">
                  <el-button type="primary" link @click.stop="handleAddSubCategory(data)">
                    <el-icon>
                      <Plus />
                    </el-icon>
                  </el-button>
                  <el-button type="primary" link @click.stop="handleEditCategory(data)">
                    <el-icon>
                      <Edit />
                    </el-icon>
                  </el-button>
                  <el-button type="danger" link @click.stop="handleDeleteCategory(node, data)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </el-button>
                </span>
              </span>
            </template>
          </el-tree>
        </el-card>
      </el-aside>

      <el-main @click="handleMainClick">
        <el-card>
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <span class="category-title">{{ currentCategory ? currentCategory.label : '全部知识' }}</span>
                <el-tag type="info" size="small" style="margin-left: 12px;">{{ knowledgeList.length }}条</el-tag>
              </div>
              <div class="header-right">
                <el-input v-model="searchKeyword" placeholder="搜索知识点" prefix-icon="Search"
                  style="width: 250px; margin-right: 16px;" />
                <el-button type="primary" @click="handleAddKnowledge">
                  <el-icon>
                    <Plus />
                  </el-icon> 添加知识
                </el-button>
              </div>
            </div>
          </template>

          <el-table :data="knowledgeList" style="width: 100%" :max-height="tableMaxHeight">
            <el-table-column prop="title" label="标题" min-width="300" show-overflow-tooltip />
            <el-table-column prop="type" label="类型" width="100" align="center">
              <template #default="scope">
                {{ getTypeText(scope.row.type) }}
              </template>
            </el-table-column>
            <el-table-column prop="importance" label="重要程度" width="100" align="center">
              <template #default="scope">
                <el-tag :type="getImportanceType(scope.row.importance)">
                  {{ scope.row.importance }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="tags" label="标签" width="200">
              <template #default="scope">
                <el-tag v-for="tag in scope.row.tags" :key="tag" type="info" size="small" style="margin-right: 4px;">
                  {{ tag }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="180" align="center" />
            <el-table-column label="操作" width="150" align="center" fixed="right">
              <template #default="scope">
                <el-button type="primary" link @click="handleEditKnowledge(scope.row)">
                  <el-icon>
                    <Edit />
                  </el-icon> 编辑
                </el-button>
                <el-button type="danger" link @click="handleDeleteKnowledge(scope.row)">
                  <el-icon>
                    <Delete />
                  </el-icon> 删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-main>
    </el-container>

    <!-- 分类对话框 -->
    <el-dialog v-model="categoryDialogVisible" :title="categoryDialogType === 'add' ? '添加分类' : '编辑分类'" width="500px">
      <el-form :model="categoryForm" label-width="80px">
        <el-form-item label="分类名称">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="上级分类">
          <el-cascader v-model="categoryForm.parent" :options="categories" :props="cascaderProps" placeholder="请选择上级分类"
            clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="categoryDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCategorySave">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 知识点对话框 -->
    <el-dialog v-model="knowledgeDialogVisible" :title="knowledgeDialogType === 'add' ? '添加知识' : '编辑知识'" width="800px">
      <el-form :model="knowledgeForm" label-width="100px">
        <el-form-item label="标题">
          <el-input v-model="knowledgeForm.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="knowledgeForm.type" placeholder="请选择类型">
            <el-option label="文本" value="文本" />
            <el-option label="图片" value="图片" />
            <el-option label="表格" value="表格" />
          </el-select>
        </el-form-item>
        <el-form-item label="重要程度">
          <el-select v-model="knowledgeForm.importance" placeholder="请选择重要程度">
            <el-option label="关键" value="关键" />
            <el-option label="重要" value="重要" />
            <el-option label="一般" value="一般" />
            <el-option label="参考" value="参考" />
            <el-option label="补充" value="补充" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-cascader v-model="knowledgeForm.categoryId" :options="categories" :props="cascaderProps" placeholder="请选择分类"
            clearable />
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="knowledgeForm.content" type="textarea" :rows="8" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="标签">
                      <el-tag v-for="tag in knowledgeForm.tags" :key="tag" type="info" closable style="margin-right: 8px;"
              @close="handleRemoveTag(tag)">
              {{ tag }}
            </el-tag>
          <el-input v-if="inputTagVisible" ref="tagInputRef" v-model="inputTagValue" class="input-new-tag" size="small"
            @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
          <el-button v-else class="button-new-tag" size="small" @click="showInput">
            + 新标签
          </el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="knowledgeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleKnowledgeSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, onUnmounted, computed, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useAppStore } from '../stores'
import { ElMessage, ElMessageBox } from 'element-plus'

const store = useAppStore()

// 搜索关键词
const searchKeyword = ref('')

// 表格最大高度
const tableMaxHeight = ref(600)

// 获取store中的响应式引用
const { categories, knowledgeItems } = storeToRefs(store)

// 树形控件配置
const defaultProps = {
  children: 'children',
  label: 'label'
}

// 级联选择器配置
const cascaderProps = {
  value: 'id',
  label: 'label',
  children: 'children',
  emitPath: false,  // 只返回选中节点的值而不是路径
  checkStrictly: true  // 允许选择任意级别节点
}

// 当前选中的分类
const currentCategory = ref(null)

// 知识列表数据（根据当前选中分类和搜索关键词过滤）
const knowledgeList = computed(() => {
  let filteredItems = knowledgeItems.value
  
  // 根据分类过滤
  if (currentCategory.value) {
    filteredItems = filteredItems.filter(item => item.categoryId === currentCategory.value.id)
  }
  
  // 根据搜索关键词过滤
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.toLowerCase().trim()
    filteredItems = filteredItems.filter(item => 
      item.title.toLowerCase().includes(keyword) ||
      item.content.toLowerCase().includes(keyword) ||
      item.tags.some(tag => tag.toLowerCase().includes(keyword)) ||
      item.type.toLowerCase().includes(keyword) ||
      item.importance.toLowerCase().includes(keyword)
    )
  }
  
  return filteredItems
})

// 分类对话框相关
const categoryDialogVisible = ref(false)
const categoryDialogType = ref('add')
const categoryForm = ref({
  id: null,
  name: '',
  parent: null
})

// 知识对话框相关
const knowledgeDialogVisible = ref(false)
const knowledgeDialogType = ref('add')
const knowledgeForm = ref({
  id: null,
  title: '',
  type: 'text',
  importance: '一般',
  content: '',
  tags: [],
  categoryId: null
})

// 标签输入相关
const inputTagVisible = ref(false)
const inputTagValue = ref('')
const tagInputRef = ref(null)

// 树组件引用
const treeRef = ref(null)

// 节点点击事件
const handleNodeClick = (data) => {
  currentCategory.value = data
  // 强制设置当前节点
  nextTick(() => {
    if (treeRef.value) {
      treeRef.value.setCurrentKey(data.id)
      // 确保高亮状态
      const currentNode = treeRef.value.getCurrentNode()
      if (currentNode && currentNode.id !== data.id) {
        treeRef.value.setCurrentKey(data.id)
      }
    }
  })
}

// 添加分类
const handleAddCategory = () => {
  categoryDialogType.value = 'add'
  categoryForm.value = {
    name: '',
    parent: null
  }
  categoryDialogVisible.value = true
}

// 添加子分类
const handleAddSubCategory = (data) => {
  categoryDialogType.value = 'add'
  categoryForm.value = {
    name: '',
    parent: data.id  // 直接使用id而不是数组
  }
  categoryDialogVisible.value = true
}

// 编辑分类
const handleEditCategory = (data) => {
  categoryDialogType.value = 'edit'
  categoryForm.value = {
    id: data.id,
    name: data.label,
    parent: null // 需要根据实际情况设置
  }
  categoryDialogVisible.value = true
}

// 删除分类
const handleDeleteCategory = (node, data) => {
  ElMessageBox.confirm(
    '删除分类将同时删除其下所有子分类和相关知识，是否继续？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      try {
        // 调用store删除分类
        store.deleteCategory(data.id)
        store.saveToStorage()
        ElMessage.success('删除成功')
      } catch (error) {
        ElMessage.error('删除失败: ' + error.message)
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 保存分类
const handleCategorySave = () => {
  try {
    if (categoryDialogType.value === 'add') {
      // 调用store添加分类
      store.addCategory(categoryForm.value)
      ElMessage.success('分类添加成功')
    } else {
      // 调用store编辑分类
      store.editCategory(categoryForm.value)
      ElMessage.success('分类编辑成功')
    }
    
    store.saveToStorage()
    categoryDialogVisible.value = false
  } catch (error) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 添加知识
const handleAddKnowledge = () => {
  knowledgeDialogType.value = 'add'
  knowledgeForm.value = {
    title: '',
    type: '文本',
    importance: '一般',
    content: '',
    tags: [],
    categoryId: currentCategory.value ? currentCategory.value.id : null
  }
  knowledgeDialogVisible.value = true
}

// 编辑知识
const handleEditKnowledge = (row) => {
  knowledgeDialogType.value = 'edit'
  knowledgeForm.value = { 
    ...row,
    type: row.type || '文本'  // 确保类型字段有默认值
  }
  knowledgeDialogVisible.value = true
}

// 删除知识
const handleDeleteKnowledge = (row) => {
  ElMessageBox.confirm(
    '确定要删除该知识点吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      try {
        // 调用store删除知识
        store.deleteKnowledge(row.id)
        store.saveToStorage()
        ElMessage.success('删除成功')
      } catch (error) {
        ElMessage.error('删除失败: ' + error.message)
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 保存知识
const handleKnowledgeSave = () => {
  try {
    if (!knowledgeForm.value.categoryId) {
      ElMessage.warning('请选择分类')
      return
    }
    
    console.log('保存知识，类型:', knowledgeDialogType.value)
    console.log('知识数据:', knowledgeForm.value)
    console.log('store方法:', Object.keys(store))
    
    if (knowledgeDialogType.value === 'add') {
      // 调用store添加知识
      store.addKnowledge(knowledgeForm.value)
      ElMessage.success('知识添加成功')
    } else {
      // 调用store编辑知识
      if (typeof store.editKnowledge === 'function') {
        store.editKnowledge(knowledgeForm.value)
        ElMessage.success('知识编辑成功')
      } else {
        console.error('editKnowledge方法不存在')
        ElMessage.error('编辑方法不存在')
      }
    }
    
    store.saveToStorage()
    knowledgeDialogVisible.value = false
  } catch (error) {
    console.error('保存知识错误:', error)
    ElMessage.error(error.message || '操作失败')
  }
}

// 显示标签输入框
const showInput = () => {
  inputTagVisible.value = true
  nextTick(() => {
    tagInputRef.value.focus()
  })
}

// 处理标签输入确认
const handleInputConfirm = () => {
  if (inputTagValue.value) {
    knowledgeForm.value.tags.push(inputTagValue.value)
  }
  inputTagVisible.value = false
  inputTagValue.value = ''
}

// 移除标签
const handleRemoveTag = (tag) => {
  const index = knowledgeForm.value.tags.indexOf(tag)
  if (index > -1) {
    knowledgeForm.value.tags.splice(index, 1)
  }
}

// 获取类型对应的中文文本
const getTypeText = (type) => {
  const typeMap = {
    'text': '文本',
    'image': '图片',
    'table': '表格',
    'Text': '文本',
    'Image': '图片',
    'Table': '表格',
    '文本': '文本',
    '图片': '图片',
    '表格': '表格'
  }
  return typeMap[type] || type
}

// 获取重要程度对应的类型
const getImportanceType = (importance) => {
  const types = {
    '关键': 'danger',
    '重要': 'warning',
    '一般': 'info',
    '参考': 'info',
    '补充': 'success'
  }
  return types[importance] || 'info'
}

// 计算表格最大高度
const calculateTableHeight = () => {
  const windowHeight = window.innerHeight
  tableMaxHeight.value = windowHeight - 240 // 减去其他元素的高度
}

// 监听窗口大小变化
window.addEventListener('resize', calculateTableHeight)

// 组件挂载时初始化
onMounted(() => {
  // 从localStorage加载数据
  store.initFromStorage()
  calculateTableHeight()
})

// 监听store状态变化并保存到localStorage
watch(
  () => store.$state,
  () => {
    store.saveToStorage()
  },
  { deep: true }
)

// 监听当前分类变化，确保树组件高亮状态正确
watch(
  () => currentCategory.value,
  (newCategory) => {
    if (newCategory && treeRef.value) {
      nextTick(() => {
        treeRef.value.setCurrentKey(newCategory.id)
      })
    }
  }
)

// 处理主内容区域点击
const handleMainClick = () => {
  // 当点击主内容区域时，重新设置树组件的当前节点
  if (currentCategory.value && treeRef.value) {
    nextTick(() => {
      treeRef.value.setCurrentKey(currentCategory.value.id)
    })
  }
}

// 定期检查并恢复高亮状态
let highlightTimer = null
const ensureHighlight = () => {
  if (currentCategory.value && treeRef.value) {
    const currentNode = treeRef.value.getCurrentNode()
    if (!currentNode || currentNode.id !== currentCategory.value.id) {
      treeRef.value.setCurrentKey(currentCategory.value.id)
    }
  }
}

// 启动定时器
onMounted(() => {
  // 从localStorage加载数据
  store.initFromStorage()
  calculateTableHeight()
  
  // 启动定时器，每100ms检查一次高亮状态
  highlightTimer = setInterval(ensureHighlight, 100)
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (highlightTimer) {
    clearInterval(highlightTimer)
  }
})
</script>

<style scoped>
.knowledge-container {
  background-color: #f5f7fa;
}

.el-container {
  height: 100%;
}

.el-aside {
  border-right: 1px solid #dcdfe6;
}

.el-main {
  padding: 0 24px;
}

.custom-tree {
  margin-top: 8px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  font-size: 14px;
}

.node-label {
  display: flex;
  align-items: center;
  gap: 4px;
}

.node-actions {
  display: none;
}

.custom-tree-node:hover .node-actions {
  display: flex;
  gap: 4px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
}

.category-title {
  font-size: 16px;
  font-weight: 500;
}

.input-new-tag {
  width: 90px;
  margin-left: 8px;
  vertical-align: bottom;
}

.button-new-tag {
  margin-left: 8px;
}

:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-button--text) {
  padding: 0 4px;
}

:deep(.el-dialog__body) {
  padding-top: 20px;
}

/* 强制保持当前节点高亮 */
:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #409eff !important;
  color: #fff !important;
}

:deep(.el-tree-node.is-current > .el-tree-node__content:hover) {
  background-color: #409eff !important;
  color: #fff !important;
}
</style>
